
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
挂机经验自动更新脚本
定期运行以更新正在挂机角色的经验
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from database.database_manager import DatabaseManager
from src.character.experience_system import ExperienceSystem
from datetime import datetime

def update_idle_experience():
    """更新挂机经验"""
    db_manager = DatabaseManager()
    exp_system = ExperienceSystem()
    
    try:
        # 查找正在挂机的角色
        query = """
        SELECT ir.id, ir.character_id, ir.location_id, c.level, ir.start_time, 
               il.base_exp_rate, ir.exp_gained,
               TIMESTAMPDIFF(SECOND, ir.start_time, NOW()) as current_duration
        FROM idle_records ir
        JOIN characters c ON ir.character_id = c.id
        JOIN idle_locations il ON ir.location_id = il.id
        WHERE ir.status = 'active'
          AND TIMESTAMPDIFF(SECOND, ir.start_time, NOW()) >= 60
        """
        
        records = db_manager.execute_query(query)
        
        if not records:
            print("没有需要更新经验的挂机角色")
            return
        
        print(f"更新 {len(records)} 个挂机角色的经验...")
        
        for record in records:
            try:
                # 计算新增经验
                duration_hours = record['current_duration'] / 3600
                base_rate = exp_system.calculate_idle_exp_rate(record['level'])
                location_multiplier = float(record['base_exp_rate'])
                
                total_exp = int(base_rate * location_multiplier * duration_hours)
                new_exp = total_exp - (record['exp_gained'] or 0)
                
                if new_exp > 0:
                    # 更新角色经验
                    update_char_query = "UPDATE characters SET exp = exp + %s WHERE id = %s"
                    db_manager.execute_update(update_char_query, (new_exp, record['character_id']))
                    
                    # 更新挂机记录
                    update_record_query = """
                    UPDATE idle_records 
                    SET exp_gained = %s, duration_seconds = %s 
                    WHERE id = %s
                    """
                    db_manager.execute_update(update_record_query, 
                                            (total_exp, record['current_duration'], record['id']))
                    
                    print(f"  角色 {record['character_id']}: +{new_exp} 经验 (总计: {total_exp})")
                
            except Exception as e:
                print(f"  更新角色 {record['character_id']} 经验失败: {e}")
        
        print("经验更新完成")
        
    except Exception as e:
        print(f"更新挂机经验失败: {e}")

if __name__ == "__main__":
    update_idle_experience()
